package com.chy.blog_web.modular.web.controller;

import cn.hutool.core.util.IdUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.chy.blog_web.core.util.PageAndParamUtil;
import com.chy.blog_web.core.util.SpaceUserUtil;
import com.chy.blog_web.core.util.UploadFileUtil;
import com.chy.blog_web.core.util.UploadURLUtil;
import com.chy.blog_web.modular.system.entity.SysMenu;
import com.chy.blog_web.modular.system.service.ISysMenuService;
import com.chy.blog_web.modular.web.entity.*;
import com.chy.blog_web.modular.web.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 描述：我的空间 controller
 * 作者：chenhuiyan
 * 时间：2020/04/11
 */
@Controller
@RequestMapping(value = "/blogSpace")
public class mySpaceController {

    /**
     * 前缀
     */
    private static String PREFIX = "web/myspace/";

    @Autowired
    private IBoInfoSetService infoSetService;

    @Autowired
    private ISysMenuService menuService;

    @Autowired
    private IBoSpaceUserService spaceUserService;

    @Autowired
    private IBoTimeLineService timeLineService;

    @Autowired
    private IBoLoveListService loveListService;

    @Autowired
    private IBoSeeBookService seeBookService;

    @Autowired
    private IBoDynamicService dynamicService;

    @Autowired
    private IBoBookService bookService;

    @Autowired
    private IBoCommentService commentService;

    /**
     * 跳转主页面
     * @return
     */
    @RequestMapping(value = "")
    public String index(){
        return PREFIX + "myspace";
    }

    /**
     * 获取基本数据
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/getInitData")
    public Map<String, Object> getInitData(HttpServletRequest request){
        Map<String, Object> res = new HashMap<>();
        try{

            BoSpaceUser spaceUser = (BoSpaceUser) request.getSession().getAttribute("spaceUser");

            Map<String, Object> params = PageAndParamUtil.getParams();

            params.put("spaceUserId", spaceUser.getId());

            List<SysMenu> menuList = menuService.getBaseMapper()
                    .selectList(new QueryWrapper<SysMenu>()
                            .eq("type", 2)
                            .eq("is_show", 0)
                            .eq("del_flag", 0)
                            .orderByAsc("sort"));

            Map<String, Object> infoSet = infoSetService.getList().get(0);

            Map<String, Object> spaceUserToHe = spaceUserService.getInfoById("", "0");

            spaceUserToHe.put("password", ""); //密码设置为空

            Map<String, Object> spaceUserToHer = spaceUserService.getInfoById("", "1");

            spaceUserToHer.put("password", ""); //密码设置为空

            List<Map<String, Object>> timeLineList = timeLineService.list(params);

            List<Map<String, Object>> loveListList = new ArrayList<>();

            List<Map<String, Object>> seeBookList = new ArrayList<>();

            //用户为其他类型时则不查未写感受的清单
            if(spaceUser.getType() != 2){

                loveListList = loveListService.list(params);

                seeBookList = seeBookService.list(params);
            }

            //亲密度
            int sweet_to_love = loveListService.getSweet();
            int sweet_to_book = seeBookService.getSweet();
            int sweet = sweet_to_love + sweet_to_book;

            res.put("menuList", menuList);
            res.put("infoSet", infoSet);
            res.put("spaceUserToHe", spaceUserToHe);
            res.put("spaceUserToHer", spaceUserToHer);
            res.put("timeLineList", timeLineList);
            res.put("loveListList", loveListList);
            res.put("seeBookList", seeBookList);
            res.put("loginUserName", spaceUser.getUserName());
            res.put("sweet", sweet);
            res.put("state", "200");
            res.put("message", "初始化成功");
        }catch (Exception e){
            e.printStackTrace();
            res.put("state", "500");
            res.put("message", "服务器异常，请重新刷新页面！");
        }

        return res;
    }


    /**
     * 获取动态
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/getDynamicList")
    public Map<String, Object> getDynamicList(){
        Map<String, Object> res = new HashMap<>();
        try {
            Map<String, Object> params = PageAndParamUtil.getParams();
            List<Map<String, Object>> dynamicList = dynamicService.list(params);
            int count = dynamicService.getCount(params);

            //处理恋爱清单动态（他她满意度、他她增加亲密值），根据写感受者类型进行处理显示各自的满意度和增加的亲密度
            for(int i = 0; i < dynamicList.size(); i++){
                if(Integer.parseInt(dynamicList.get(i).get("suType") + "") == 0){ //她

                    dynamicList.get(i).put("satisfiedValue", dynamicList.get(i).get("heSatisfiedValue")); //他满意度
                    dynamicList.get(i).put("loveSweet", dynamicList.get(i).get("heSweet")); //他满意度

                }else if(Integer.parseInt(dynamicList.get(i).get("suType") + "") == 1){ //她
                    dynamicList.get(i).put("satisfiedValue", dynamicList.get(i).get("herSatisfiedValue")); //她满意度
                    dynamicList.get(i).put("loveSweet", dynamicList.get(i).get("herSweet")); //她满意度
                }
            }

            res.put("dynamicList", dynamicList);
            res.put("count", count);
            res.put("state", "200");
            res.put("message", "动态获取成功");
        }catch (Exception e){
            e.printStackTrace();
            res.put("state", "500");
            res.put("message", "服务器异常，获取动态失败");
        }

        return res;
    }

    /**
     * 跳转发起恋爱清单页面
     * @return
     */
    @RequestMapping(value = "sendLoveListIndex")
    public String sendLoveListIndex(){
        return PREFIX + "loveList/loveList_add";
    }

    /**
     * 发起恋爱清单
     * @param boLoveList
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/sendLoveList")
    public Map<String, Object> sendLoveList(BoLoveList boLoveList, HttpServletRequest request){

        Map<String, Object> res = new HashMap<>();
        try {

            BoSpaceUser spaceUser = (BoSpaceUser) request.getSession().getAttribute("spaceUser");

            if(spaceUser.getType() == 2){
                res.put("state", "500");
                res.put("message", "您无权限发布恋爱清单");
                return res;
            }

            loveListService.sendLoveList(boLoveList, spaceUser);
            res.put("state", "200");
            res.put("message", "发起恋爱清单成功");
        }catch (Exception e){
            e.printStackTrace();
            res.put("state", "500");
            res.put("message", "服务器异常，发起失败！");
        }
        return res;
    }

    /**
     * 跳转发起一起看书页面
     * @return
     */
    @RequestMapping(value = "/sendSeeBookIndex")
    public String sendSeeBookIndex(){
        return PREFIX + "seeBook/seeBook_add";
    }

    /**
     * 发起一起看书
     * @param seeBook
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/sendSeeBook")
    public Map<String, Object> sendSeeBook(BoSeeBook seeBook, HttpServletRequest request){
        Map<String, Object> res = new HashMap<>();
        try {

            BoSpaceUser spaceUser = (BoSpaceUser) request.getSession().getAttribute("spaceUser");

            if(spaceUser.getType() == 2){
                res.put("state", "500");
                res.put("message", "您无权限发布看书清单");
                return res;
            }

            seeBookService.sendSeeBook(seeBook, spaceUser);
            res.put("state", "200");
            res.put("message", "发起看书清单成功");
        }catch (Exception e){
            e.printStackTrace();
            res.put("state", "500");
            res.put("message", "服务器异常，发起约看书失败");
        }
        return res;
    }

    /**
     * 获取书籍树列表
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/getBookTree")
    public Map<String, Object> getBookTree(){
        Map<String, Object> res = new HashMap<>();
        try{
            Map<String, Object> params = new HashMap<>();
            List<Map<String, Object>> treeList = bookService.getBookTreeToS(params);
            res.put("state", "200");
            res.put("message", "初始化书籍树成功");
            res.put("treeList", treeList);
        }catch (Exception e){
            e.printStackTrace();
            res.put("state", "500");
            res.put("message", "初始化书籍树失败");
        }
        return res;
    }

    /**
     * 发起普通动态、写恋爱清单感受、写约看书感受
     * @param type 0恋爱清单感受，1约看书感受，4其他
     * @param serviceId 写感受业务编辑
     * @return
     */
    @RequestMapping(value = "/sendDynamicindex")
    public String sendDynamicindex(Integer type, String serviceId, Model model){
        model.addAttribute("type", type);
        model.addAttribute("serviceId", serviceId);
        model.addAttribute("dynamicId", IdUtil.simpleUUID()); //提前生成id
        return PREFIX + "dynamic/dynamic_add";
    }


    /**
     * 发动态、写感爱
     * @param dynamic
     * @param satisfied 满意度（0非常不满意，1不满意，2满意，3很满意，4非常满意）
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/sendDynamic")
    public Map<String, Object> sendDynamic(BoDynamic dynamic, Integer satisfied, HttpServletRequest request){
        Map<String, Object> res = new HashMap<>();
        try {
            BoSpaceUser spaceUser = (BoSpaceUser) request.getSession().getAttribute("spaceUser");
            dynamicService.sendDynamic(dynamic, satisfied, spaceUser);
            res.put("state", "200");
            res.put("message", "发布成功");
        }catch (Exception e){
            e.printStackTrace();
            res.put("state", "500");
            res.put("message", "发布失败");
        }
        return res;
    }

    /**
     * 根据编辑获取看书信息
     * @param serviceId
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/getSeeBookInfo")
    public Map<String, Object> getSeeBookInfo(String serviceId){
        Map<String, Object> res = new HashMap<>();
        try{
            res = seeBookService.getInfoById(serviceId);
            res.put("state", "200");
            res.put("message", "初始化看书信息成功");
        }catch (Exception e){
            e.printStackTrace();
            res.put("state", "500");
            res.put("message", "初始化看书信息失败");
        }
        return res;
    }

    /**
     * 根据编辑获取恋爱清单信息
     * @param serviceId
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/getLoveListInfo")
    public Map<String, Object> getLoveListInfo(String serviceId){
        Map<String, Object> res = new HashMap<>();
        try{
            res = loveListService.getInfoById(serviceId);
            res.put("state", "200");
            res.put("message", "初始化恋爱清单信息成功");
        }catch (Exception e){
            e.printStackTrace();
            res.put("state", "500");
            res.put("message", "初始化恋爱清单信息失败");
        }
        return res;
    }

    /**
     * 上传照片并生成缩略图
     * @param file
     * @param dynamicId
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/uploadImg")
    public Map<String, Object> uploadImg(MultipartFile file, String dynamicId){

        Map<String, Object> res = dynamicService.uploadImg(file, dynamicId);

        return res;
    }

    /**
     * 修改空间用户资料
     * @param model
     * @return
     */
    @RequestMapping(value = "/spaceUserEdit")
    public String spaceUserEdit(Model model, HttpServletRequest request){
        BoSpaceUser spaceUser = (BoSpaceUser) request.getSession().getAttribute("spaceUser");
        model.addAttribute("id", spaceUser.getId());
        return PREFIX + "spaceUser/spaceUser_edit";
    }

    /**
     * 获取空间用户详情
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/getUserInfoById")
    public Map<String, Object> getUserInfoById(HttpServletRequest request){
        Map<String, Object> res = new HashMap<>();
        try {
            BoSpaceUser spaceUser = (BoSpaceUser) request.getSession().getAttribute("spaceUser");
            res.put("spaceUser", spaceUser);
            res.put("state", "200");
            res.put("message", "获取成功");
        }catch (Exception e){
            res.put("state", "500");
            res.put("message", "获取失败");
        }
        return res;
    }

    /**
     * 保存空间用户
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/saveSpaceUser")
    public Map<String, Object> saveSpaceUser(BoSpaceUser spaceUser, HttpServletRequest request){
        Map<String, Object> res = new HashMap<>();
        try {
            if(!"".equals(spaceUser.getPassword()) && spaceUser.getPassword() != null){
                spaceUser.setPassword(SecureUtil.md5(spaceUser.getPassword()));
            }else{
                spaceUser.setPassword(null);
            }
            spaceUserService.updateById(spaceUser);
            spaceUser = spaceUserService.getById(spaceUser.getId());
            request.getSession().setAttribute("spaceUser", spaceUser);
            res.put("state", "200");
            res.put("message", "保存成功");
        }catch (Exception e){
            res.put("state", "500");
            res.put("message", "保存失败");
        }
        return res;
    }

    /**
     * 上传头像
     * @param file
     * @return
     */
    @RequestMapping(value = "/uploadHeadPhoto")
    @ResponseBody
    public Map<String, Object> uploadHeadPhoto(MultipartFile file){
        //上传
        Map<String, Object> res = UploadFileUtil.fileUploadToOne(file, UploadURLUtil.HEAD_PHOTO, false);

        return res;
    }

    /**
     * 评论
     * @param comment
     * @return
     */
    @RequestMapping(value = "/sendRepy")
    @ResponseBody
    public Map<String, Object> sendRepy(BoComment comment, HttpServletRequest request){
        Map<String, Object> res = new HashMap<>();
        try {
            BoSpaceUser spaceUser = (BoSpaceUser) request.getSession().getAttribute("spaceUser");

            comment.setHeadPhoto(spaceUser.getHeadUrl());
            if(comment.getType() == 0){ //评论
                comment.setUserName(spaceUser.getId()); //评论者昵称保存空间用户编号
            }else{ //回复
                comment.setByUserName(spaceUser.getId()); //回复者昵称保存空间用户编号
            }
            comment.preInsert();
            commentService.save(comment);
            res.put("state", "200");
            res.put("message", "评论成功");
        }catch (Exception e){
            e.printStackTrace();
            res.put("state", "500");
            res.put("message", "服务器异常，评论失败");
        }
        return res;
    }

    /**
     * 进入看书页面
     * @param model
     * @return
     */
    @RequestMapping(value = "/toSeeBook")
    public String toSeeBook(Model model){
        return PREFIX + "seeBook/toSeeBook";
    }

    /**
     * 获取看书信息
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/getSeeBookTreeDetail")
    public Map<String, Object> getSeeBookTreeDetail(){
        Map<String, Object> res = new HashMap<>();
        try{
            Map<String, Object> params = PageAndParamUtil.getParams();
            List<Map<String, Object>> seeBookList = seeBookService.getList(params);

            String[] bookIdArr = new String[seeBookList.size()];
            String directoryStr = ""; //目录
            String bookListStr = ""; //章节
            for(int l = 0; l < seeBookList.size(); l++){
                bookIdArr[l] = seeBookList.get(l).get("bookId") + "";
                directoryStr += seeBookList.get(l).get("directoryName") + ",";
                bookListStr += seeBookList.get(l).get("bookListName") + ",";
            }

            params.put("bookIdArr", bookIdArr);
            List<Map<String, Object>> treeList = bookService.getBookTree(params);

            String[] directoryArr = directoryStr.split(","); //目录
            String[] bookListArr = bookListStr.split(","); //章节

            //****************提取看书清单的目录和章节********************

            //书列表
            List<Map<String, Object>> bookList = new ArrayList<>();

            for(int x = 0; x < treeList.size(); x++){

                //创建一本书
                Map<String, Object> bookMap = new HashMap<>();
                bookMap.put("id", treeList.get(x).get("id"));
                bookMap.put("title", treeList.get(x).get("title"));
                bookMap.put("content", treeList.get(x).get("content"));
                bookMap.put("type", treeList.get(x).get("type"));
                bookMap.put("author", treeList.get(x).get("author"));
                bookMap.put("bookType", treeList.get(x).get("bookType"));
                bookMap.put("spread", true);
                List<Map<String, Object>> children = (List<Map<String, Object>>)treeList.get(x).get("children"); //目录
                List<Map<String, Object>> dirList = new ArrayList<>(); //保存目录列表
                for(int i = 0; i < directoryArr.length; i++){
                    for(int j = 0; j < children.size(); j++){
                        if(directoryArr[i].equals(children.get(j).get("title"))){
                            Map<String, Object> createDir = new HashMap<>(); //创建目录
                            createDir.put("id", children.get(j).get("id"));
                            createDir.put("title", children.get(j).get("title"));
                            createDir.put("content", children.get(j).get("content"));
                            createDir.put("type", children.get(j).get("type"));
                            createDir.put("spread", true);
                            List<Map<String, Object>> childrenToList = (List<Map<String, Object>>)children.get(j).get("children"); //目录章节
                            List<Map<String, Object>> listList = new ArrayList<>(); //保存章节列表
                            for(int k = 0; k < bookListArr.length; k++){
                                for(int m = 0; m < childrenToList.size(); m++){
                                    if(bookListArr[k].equals(childrenToList.get(m).get("title"))){
                                        Map<String, Object> createList = new HashMap<>(); //创建章节
                                        createList.put("id", childrenToList.get(m).get("id"));
                                        createList.put("title", childrenToList.get(m).get("title"));
                                        createList.put("type", childrenToList.get(m).get("type"));
                                        createList.put("remark", childrenToList.get(m).get("remark"));
                                        createList.put("content", childrenToList.get(m).get("content"));
                                        listList.add(createList);
                                        break;
                                    }
                                }
                            }
                            createDir.put("children", listList);
                            dirList.add(createDir);
                            break;
                        }
                    }
                }
                bookMap.put("children", dirList);
                bookList.add(bookMap);
            }

            //看书清单的开始时间与现在时间差（分钟）
            Calendar calendar = Calendar.getInstance();

            long nowDateTime = calendar.getTimeInMillis(); //现在的时间戳
            long startTime = 0; //开始看书的时间戳
            long endTime = 0; //结束看书的时间戳
            long sbetween_minu = 0; //开始看书和现在时间相差的分钟,小于0，则已开始
            long ebetween_minu = 0; //结束看书和现在时间相差的分钟,小于0，则看书时间已过

            List<Map<String, Object>> seeBookTime = new ArrayList<>(); //保存看书时间信息

            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

            for(Map<String, Object> map: seeBookList){

                //开始看书和现在时间相差的分钟,小于0，则已开始
                calendar.setTime(simpleDateFormat.parse(map.get("startTime").toString()));
                startTime = calendar.getTimeInMillis(); //开始时间的时间戳
                sbetween_minu = (startTime - nowDateTime) / (1000 * 60);

                //结束看书和现在时间相差的分钟,小于0，则看书时间已过
                calendar.setTime(simpleDateFormat.parse(map.get("endTime").toString()));
                endTime = calendar.getTimeInMillis(); //结束时间的时间戳
                ebetween_minu = (endTime - nowDateTime) / (1000 * 60);

                Map<String, Object> bookTimeIfo = new HashMap<>();
                bookTimeIfo.put("bookName", map.get("bookName").toString());
                bookTimeIfo.put("startTime", map.get("startTime").toString());
                bookTimeIfo.put("endTime", map.get("endTime").toString());
                bookTimeIfo.put("sbetween_minu", sbetween_minu);
                bookTimeIfo.put("ebetween_minu", ebetween_minu);
                seeBookTime.add(bookTimeIfo);
            }

            res.put("state", "200");
            res.put("message", "初始化书籍树成功");
            res.put("treeList", bookList);
            res.put("seeBookTime", seeBookTime);
        }catch (Exception e){
            e.printStackTrace();
            res.put("state", "500");
            res.put("message", "初始化书籍树失败");
        }
        return res;
    }

}
